package com.example.shushiyunsst.fragment.main.home.child.miner22.mother_icon

import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseDataBindingFragment
import com.example.library_common.global.AppGlobals
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.QMUIDisplayHelper
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.MotherIconInfoHeaderFragmentBinding
import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.fragment.main.constant.CURRENT_DEVICE_TOKEN
import com.example.shushiyunsst.fragment.main.home.child.bean.MotherIconBean
import com.example.shushiyunsst.fragment.main.home.child.miner22.CMLCollectionFragment
import com.example.shushiyunsst.fragment.main.home.child.miner22.CMLTransferFragment
import com.example.shushiyunsst.fragment.main.home.child.miner22.bean.CMLIntent
import com.example.shushiyunsst.fragment.main.home.child.miner22.mother_icon.adapter.MotherIconBannerAdapter
import com.example.shushiyunsst.util.PayingPassWordVerifyPop
import com.example.shushiyunsst.util.clipboard
import com.example.wallet.db.UserInfoManager
import com.example.wallet.utils.Preference
import com.google.android.material.snackbar.Snackbar
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import com.youth.banner.indicator.CircleIndicator

class MotherIconInfoHeaderFragment :
    BaseDataBindingFragment<MotherIconInfoHeaderFragmentBinding>(), View.OnClickListener {

    companion object {
        fun newInstance(): MotherIconInfoHeaderFragment {
            val args = Bundle()
            val fragment = MotherIconInfoHeaderFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var onActive = false

    private var motherIconInterfaces: MotherIconInterfaces? = null

    private var mBannerLayoutHeight = 0

    private var mBannerAdapter: MotherIconBannerAdapter? = null

    fun setMotherIconInterfaces(motherIconInterfaces: MotherIconInterfaces?) {
        this.motherIconInterfaces = motherIconInterfaces
    }

    fun setEntity(mBean: MotherIconBean?) {
        viewBinder.entity = mBean
        mBannerAdapter?.addAll(viewBinder.entity?.imageList)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport = false
        val screenWidth =
            QMUIDisplayHelper.getScreenWidth(com.example.wallet.global.AppGlobals.getApplication())
        mBannerLayoutHeight = screenWidth / 2

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewBinder.onViewClick = this
        val lp = viewBinder.mBannerLayout.layoutParams
        if (lp != null && lp.height != mBannerLayoutHeight) {
            lp.height = mBannerLayoutHeight
            viewBinder.mBannerLayout.layoutParams = lp
        }

        mBannerAdapter = MotherIconBannerAdapter(mutableListOf(), _mActivity)

        viewBinder.mBanner.adapter = mBannerAdapter
        viewBinder.mBanner.indicator = CircleIndicator(context)
        viewBinder.mBanner.addBannerLifecycleObserver(this)
        mBannerAdapter?.addAll(viewBinder.entity?.imageList)

    }

    override fun layoutId(): Int {
        return R.layout.mother_icon_info_header_fragment
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.mActive -> {
                val entity = viewBinder.entity
                if (entity?.isActiveScml() == true) {
                    Toast.makeText(_mActivity, "已激活母币矿池", Toast.LENGTH_SHORT).show()
                    return
                }

                if (!onActive) {
                    onActive = true
                    onActive()
                }
            }

            R.id.transfer -> {
                val entity = viewBinder.entity
                val address = entity?.walletAddress ?: ""
                val bean = CMLIntent(
                    address,
                    entity?.scmlBalance.toString(),
                    entity?.tokenType ?: "",
                    entity?.accountType ?: "",
                    CMLIntent.MOTHER_ACCOUNT
                )
                start(CMLTransferFragment.newInstance(bean))
            }

            R.id.mCopyTv -> {
                clipboard("addressTv", viewBinder.entity?.walletAddress ?: "")
            }

            R.id.withdraw -> {
                val entity = viewBinder.entity
                val address = entity?.walletAddress ?: ""
                val bean = CMLIntent(
                    address,
                    entity?.scmlBalance.toString(),
                    entity?.tokenType ?: "",
                    entity?.accountType ?: "",
                    CMLIntent.MOTHER_ACCOUNT
                )
                start(CMLCollectionFragment.newInstance(bean))
            }

            R.id.synthesis -> {
                onCompound()
            }
        }
    }

    //合成母币
    private fun onCompound() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val payPasswd = userInfo?.payPasswd ?: ""
        if (payPasswd.isEmpty()) {
            Toast.makeText(_mActivity, "请设置支付密码", Toast.LENGTH_SHORT).show()
            return
        }

        val mCompoundInputValueStr = viewBinder.mCompoundInputValue.text?.toString() ?: ""
        if (mCompoundInputValueStr.isEmpty()) {
            Toast.makeText(_mActivity, "请输入合成数量", Toast.LENGTH_SHORT).show()
            return
        }


        val mPop = PayingPassWordVerifyPop(_mActivity)
        XPopup.Builder(_mActivity)
            .setPopupCallback(object : SimpleCallback() {
                override fun onDismiss(popupView: BasePopupView?) {
                    super.onDismiss(popupView)
                    if (mPop.getIsOnVerifyPop()) {
                        if (mPop.getVerifyPop()) {
//                            motherIconInterfaces?.showRefresh()
                            compoundNow()
                        } else {
                            Toast.makeText(_mActivity, "支付密码错误", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            })
            .asCustom(mPop)
            .show()

//        val pop = MotherIconSynthesisPop(_mActivity).setData(entity)
//
//        XPopup.Builder(_mActivity)
//            .hasShadowBg(false)
//            .setPopupCallback(object : SimpleCallback() {
//                override fun onDismiss(popupView: BasePopupView?) {
//                    super.onDismiss(popupView)
//                    if (pop.dataSend) {
//                        motherIconInterfaces?.onRefresh()
//                    }
//
//                    if (pop.mMoneyEmptyV) {
//                        val parentFragment = parentFragment
//                        if (parentFragment is BaseFragmentEx) {
//                            parentFragment.start(MainFragment.newInstance(), SINGLETASK)
//                        } else {
//                            start(MainFragment.newInstance(), SINGLETASK)
//                        }
//
//                        EventBus.getDefault().post(MessageWrap.getInstance(SHOW_BUYING_PAGE_CML))
//                    }
//                }
//            })
//            .moveUpToKeyboard(true)
//            .asCustom(pop)
//            .show()
    }

    private fun compoundNow() {
//        val entity = viewBinder.entity
        val mCountValueStr = viewBinder.mCompoundInputValue.text?.toString() ?: ""

        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val maps = mapOf(
            "txNums" to mCountValueStr,
            "uid" to "${userInfo?.uid}"
        )

        RestClient.builder()
            .url(R.string.mixScml)
            .raw(JSON.toJSONString(maps))
            .success {
                Toast.makeText(context, "合成成功", Toast.LENGTH_SHORT).show()
                getUserBalanceInfo(AppGlobals.getApplication())
                motherIconInterfaces?.onRefresh()
                viewBinder.mCompoundInputValue.setText("")
            }.failure {

                Toast.makeText(context, "合成失败", Toast.LENGTH_SHORT).show()
                motherIconInterfaces?.onRefresh()
            }.error { _, msg ->
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                motherIconInterfaces?.onRefresh()

            }
            .build()
            .post()
    }

    private fun onActive() {
        val entity = viewBinder.entity
        if ((entity?.scmlBalance ?: 0.0) <= 0.0) {
            Snackbar.make(
                viewBinder.root, "暂无可激活的母币",
                Snackbar.LENGTH_LONG
            )
                .addCallback(object : Snackbar.Callback() {
                    override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
                        super.onDismissed(transientBottomBar, event)
                        onActive = false
                    }
                })
                .show()
            onActive = false
            return
        }
        Snackbar.make(
            viewBinder.root, "激活母币需要冻结${entity?.activeScmlLockNeedCmlNums}CML子币",
            Snackbar.LENGTH_LONG
        )
            .addCallback(object : Snackbar.Callback() {
                override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
                    super.onDismissed(transientBottomBar, event)
                    onActive = false
                }
            })
            .setAction("确定") {
                sendOnActive()
            }
            .show()
    }

    private fun sendOnActive() {
        val deviceTokens = Preference.HOLDER.getCustomAppProfile(CURRENT_DEVICE_TOKEN)
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val maps = mapOf(
            "uid" to userInfo?.uid,
            "deviceToken" to deviceTokens
        )
        RestClient.builder()
            .url(R.string.activeScml)
            .raw(JSON.toJSONString(maps))
            .success {
                onActive = false
                Toast.makeText(_mActivity, "激活成功", Toast.LENGTH_SHORT).show()

                motherIconInterfaces?.onRefresh()
            }.failure {
                onActive = false
                Toast.makeText(_mActivity, "激活失败", Toast.LENGTH_SHORT).show()
            }.error { _, msg ->
                onActive = false
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()

            }
            .build()
            .post()
    }

    override fun onDestroy() {
        super.onDestroy()
        motherIconInterfaces = null
    }

}